<template>
<!-- 经销商 -->
    <div class="dhzn_roledealer">

        <!-- 列表-->
        <div v-if="pageingstate !== 1" class="d_rd-first">
            <!-- 头部的添加 数量 以及搜索 -->
            <div class="d_rd-title br5 bcwh p10">
                <div class="d_rd-t-search mt10">
                    <button type="button" class="bc4a wh p10 br5 mr10 mb10" @click="pageingstate = 1">添加经销商</button>
                    <el-form :model="formstate" ref="formstate" label-width="50px">
                        <el-form-item label='筛选'>
                            <el-col :span="3">
                                <el-select v-model="formstate.state">
                                    <el-option label="不限" value=""></el-option>
                                    <el-option label="已冻结" value="0"></el-option>
                                    <el-option label="正常" value="1"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="3">
                                <el-select v-model="formstate.select" @change=";for(var i in formstate) i!=='state' && i!=='select'? formstate[i] = '' : ''">
                                    <el-option label="用户名" value="0"></el-option>
                                    <el-option label="所在城市" value="1"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="12">
                                <el-input v-if="formstate.select === '0'" v-model="formstate.username" placeholder="请输入用户名后进行搜索" clearable></el-input>
                                <el-cascader v-else class="search-cascader" :options="cityOptions" v-model="formstate.provinces" @change="changeProvince"></el-cascader>
                            </el-col>

                            <el-col :span="6" class="tc">
                                <el-button type="primary" @click="searchlist(),currentPage=1">搜索</el-button>
                                <el-button type="danger" @click="requestfrolirm(),currentPage=1;for(var i in formstate) i!=='state' && i!=='select'? formstate[i] = '' : ''">取消</el-button>
                            </el-col>
                        </el-form-item>
                    </el-form>
                </div>
                <span class='d_rd-t-num tc wh dib br5 p10'>经销商总数:<span>{{number}}</span></span>
            </div>
            <!-- <hr> -->
            <!-- 内容也就是数据列表 -->
            <div class="d_rd-list bcwh br5 mt10 p10">
                <table class="d_rd-l-table tc">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>登录密码<br><span class="b00a n f12">*鼠标进过查看密码</span></th>
                            <th>上级ID</th>
                            <th>经销商等级</th>
                            <th>状态</th>
                            <th>下级经销商数</th>
                            <th>下级企业经销商数</th>
                            <th>经销商会员数</th>
                            <th>入驻时间</th>
                            <th>所在城市</th>
                            <th>详细地址</th>
                            <th>经销商姓名</th>
                            <th>所属企业ID</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody class="f14">
                        <tr v-for="(item,key) in frolirmlist" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.username}}</td>
                            <td class="d_rd-l-t-tbody-pwd"><span>{{item.password | filterpwd}}</span><span class="dn b00a">{{item.password}}</span></td>
                            <td>{{item.topid | filtertopid}}</td>
                            <td><span v-show="item.level !== 0">{{item.level}}</span>经销商</td>
                            <td>{{item.state | filterstate}}</td> 
                            <td>{{item.subNumber}}</td>
                            <td>{{item.storesNum}}</td>
                            <td>{{item.memberNum}}</td>
                            <td>{{item.createTime*1000 | formatDate}} {{item.createTime*1000 | formatDateBehind}}</td>
                            <td>{{item.city}}</td>
                            <td>{{item.address}}</td>
                            <td>{{item.name}}</td>
                            <td>{{item.enterpriseid}}</td>
                            <td>
                                <button type="button" @click="centerDialog=true;for(var i in rolesupdata) i!=='state' ? rolesupdata[i]=item[i] : rolesupdata[i]=String(item[i]);rolesupdata.key=key" class="bc4a wh br5 p5 whn"><i class="el-icon-edit"></i>编辑</button>
                                <button type="button" @click="freeze(item.id,item.state,key)" class="bcfd wh br5 p5 whn">冻结<i class="el-icon-close"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div class="d_g-lblock mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

                <!-- 编辑修改的弹窗 -->
                <el-dialog title="修改" :visible.sync="centerDialog" width="30%" center>
                    
                    <el-form :model="rolesupdata" ref="rolesupdata" :rules="rules" label-width="80px">

                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="rolesupdata.username" placeholder="请输入新的用户名" clearable></el-input>
                        </el-form-item>

                        <el-form-item label="登录密码" prop="password">
                            <el-input v-model="rolesupdata.password" placeholder="请输入新的登录密码" clearable></el-input>
                        </el-form-item>

                        <el-form-item label="账号状态">
                            <!-- <el-input v-model="rolesupdata.username" placeholder="请输入新的用户名" clearable></el-input> -->
                            <el-select v-model="rolesupdata.state">
                                <el-option label="冻结" value="0"></el-option>
                                <el-option label="正常" value="1"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="详细地址" prop="address">
                            <el-input v-model="rolesupdata.address" placeholder="请输入新经销商地址" clearable></el-input>
                        </el-form-item>

                    </el-form>

                    <span slot="footer" class="dialog-footer">
                        <el-button @click="centerDialog=false">取消</el-button>
                        <el-button type="primary" @click="updataroles('rolesupdata')">确定</el-button>
                    </span>
                </el-dialog>
            </div>

        </div>
        <!-- 添加 -->
        <div v-else class="d_rd-second bcwh br5">
            <div class="wh bb1 p10 mb10"><span @click="pageingstate = 0" class="bc4a wh br5 dib f14 p10">回列表页</span></div>
            <el-form :model="rolesadd" ref="rolesadd" :rules="rules" label-width="80px">

                <el-form-item label="用户名" prop="username">
                    <el-col :span="6"><el-input v-model="rolesadd.username" placeholder="请输入用户名" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item prop="password" label="登录密码">
                    <el-col :span="6"><el-input v-model="rolesadd.password" placeholder="请输入登录密码" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item label="经销级别" prop="level">
                    <el-select v-model="rolesadd.level" placeholder="请选设置新增经销商级别" @change="gradeselect">
                        <el-option label="经销商" :value="0"></el-option>
                        <el-option label="1经销商" :value="1"></el-option>
                        <el-option label="2经销商" :value="2"></el-option>
                        <el-option label="3经销商" :value="3"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="经销上级" prop="topid">
                    <el-select v-model="rolesadd.topid" placeholder="请选择上级经销商" :disabled="rolesadd.level === 0 ? true : false">
                        <el-option label="经销商" :value="0" v-if="rolesadd.level===0"></el-option>
                        <el-option v-for="(item,key) in selectdealer" :key="key" :label="item.name+'('+item.level+'级)'" :value="item.id" :disabled="item.level === rolesadd.level-1 ? false : true"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="provinces" label="所在城市">
                    <el-cascader :options="cityOptions" v-model="rolesadd.provinces" @change="changeProvince" clearable></el-cascader>
                </el-form-item>

                <el-form-item prop="address" label="详细地址">
                    <el-col :span="6"><el-input v-model="rolesadd.address" clearable :disabled="rolesadd.provinces==undefined || rolesadd.provinces=='' ? true : false" placeholder="请输入经销商的详细地址"></el-input></el-col>
                </el-form-item>

                <el-form-item label="老板姓名" prop="name">
                    <el-col :span="6"><el-input v-model="rolesadd.name" placeholder="请输入经销商注册名称" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item label="所属企业" prop="enterpriseid">
                    <el-select v-model="rolesadd.enterpriseid" placeholder="请选择所在企业" clearable>
                        <el-option v-for="(item,key) in selectlevel" :key="key" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="addroles('rolesadd')">提交</el-button>
                </el-form-item>
            </el-form>
        </div>


    </div>
</template>

<script>
import cityOptions from '../../js/city_data2017_element.js'
const axios = require('axios')
import {formatDate} from '../../js/time.js';
let that
export default {
    components: {},
    data() {
        return {
            frolirmlist: '',
            number:'',
            city1:'',
            token: '',                          //登录权限令牌
            rolestate: '',                      //路由传值，十种不同身份判断使用
            pageingstate: 0,
            selectlevel:{},                     //用来添加修改上级合伙人id使用的
            //查询的绑定值
            formstate:{
                state: '',
                select: '0',
                username: '',
                provinces: '',
                city: ''
            },
            // 修改的绑定对象
            rolesupdata: {
                id: '',
                username: '',
                password: '',
                state: '',
                address: '',
                // provinces: '',
            },
            // 添加经销商
            rolesadd:{
                username: '',
                password: '',
                topid: 0,
                level: 0,
                enterpriseid: '',
				provinces: '',
                city: '',
                address: '',
                name: ''
            },
            rules:{
                username: [
                    {required:true,message:'请输入用户名',trigger:'blur'}
                ],
                password: [
                    {required:true,message:'请输入登录密码',trigger:'blur'}
                ],
                enterpriseid: [
                    {required:true,message:'请选择上级企业',trigger:'change'}
                ],
                level: [
                    {required:true,message:'请选择经销商级别',trigger:'change'}
                ],
                topid: [
                    {required:true,message:'请选择经销商归属',trigger:'blur'}
                ],
                address: [
                    {required:true,message:'请输入经销商地址',trigger:'blur'}
                ],
                provinces: [
                    {required:true,message:'请选择所在城市',trigger: 'change'}
                ],
                name: [
                    {required:true,message:'请输入经销商姓名',trigger:'blur'}
                ]
            },
            centerDialog: false,                //弹窗的状态
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            cityOptions: cityOptions,
        };
    },
    filters:{
        filterstatus(level){
            if(level === 0){
                level = '经销商'
            }else if(level === 1){
                level = "一级经销商"
            }else{
                level = '二级经销商'
            }
            return level
        },
        filterstate(state){
            if(state === 0){
                state = '冻结'
            }else{
                state = '正常'
            }
            return state
        },
        filtertopid(topid){
            that.selectdealer.forEach((item)=>{
                if(topid === 0){
                    topid = '顶级经销商'
                }else{
                    item.id===topid ? topid = item.name : '';
                }
            })
            return topid
        },
        // 时间戳转换
        formatDate(time){
            var date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd')
        },
        formatDateBehind(time){
            var date = new Date(time);
            return formatDate(date,'hh:mm:ss')
        },
        //密码转成星号
        filterpwd(pwd){
            return pwd = pwd.replace(/./g,'*')
        } 
    },
    computed: {},
    watch: {},
    methods: {
        requestfrolirm(){
            let that = this;
            let data = {current: that.currentPage,size: that.pagesize};
            let updata = JSON.stringify(data);
            // console.log(updata)
            axios({
                method: 'post',
                url: '/api/dealer/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log(resp)
                that.frolirmlist = resp.data.data;
                that.total = resp.data.code;
                that.number = resp.data.code;
                that.pageningstate = 0;
            }).catch( err=> {console.log(err)})
        },

        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            this.requestfrolirm()
            // if(that.paging === 1){
            //     that.classifylatt()
            // }else if(that.paging === 2){
            //     that.lookson()
            // }else if(that.paging === 3){
            //     that.inquire()
            // }else{
            //     that.updataclassify()
            // }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            const that = this;
            that.currentPage = val;
            that.requestfrolirm()
            // if(that.paging === 1){
            //     that.classifylatt()
            // }else if(that.paging === 2){
            //     that.lookson()
            // }else if(that.paging === 3){
            //     that.inquire()
            // }else{
            //     that.updataclassify()
            // }
        },

        // 省市区级联选择器组件
        changeProvince(){
            let that = this;
            if(that.pageingstate === 0){
                that.formstate.provinces.forEach(ment => {
                    if(ment.charAt(ment.length-1) === '市' || ment.substring(ment.length-3) === '行政区' || ment === '台湾省'){
                        that.formstate.city = ment
                    }
                });
            }else{
                that.rolesadd.address = '';
                that.rolesadd.provinces.forEach(ment => {
                    if(ment.charAt(ment.length-1) === '市' || ment.substring(ment.length-3) === '行政区' || ment === '台湾省'){
                        that.rolesadd.city = ment
                    }
                    that.rolesadd.address += ment
                });
            }
            
        },

        // 添加经销商
        addroles(firmadd){
            let that = this;
            that.$refs[firmadd].validate((valid)=>{
                if(valid){
                    console.log('验证通过')
                    let data = {state: 1};
                    for(var i in that.rolesadd) i!=='provinces' ? data[i] = that.rolesadd[i] : '';
                    let updata = JSON.stringify(data);
                    console.log(data,updata)
                    axios({
                        method: 'post',
                        url: '/api/dealer/add',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        if(resp.data.message === '请求成功'){
                            data.id = resp.data.data;
                            that.frolirmlist.length<that.pagesize ? that.frolirmlist.push(data) : '';
                            that.pageingstate = 0;
                            that.number += 1;
                            that.selectdealer.push({id:resp.data.data,name:data.name,level:data.level})
                            for(var t in that.rolesadd) t!=='level' ? that.rolesadd[t] = '' : that.rolesadd[t] = 0;
                        }
                    }).catch( err=> {console.log(err)})
                }
            })
        },

        // 搜索
        searchlist(){
            let that = this;
            let data = {current: that.currentPage,size: that.pagesize};
            for(var i in that.formstate) i!=="select" && i!=='provinces' && that.formstate[i]!=='' ? data[i] = that.formstate[i] : '';
            let updata = JSON.stringify(data)
            // console.log(updata)
            axios({
                method: 'post',
                url: '/api/dealer/list',
                headers: {
                    'Content-type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log(resp)
                if(resp.data.message === '请求成功' && resp.data.data !== ''){
                    that.pageningstate = 2;
                    resp.data.code === 0 ? (
                        that.$message('搜索的数据不存在')
                    ) : (
                        that.$message({
                            message: '成功找到'+resp.data.code+'条数据',
                            type: 'success'
                        }),
                        that.frolirmlist = resp.data.data,
                        that.total = resp.data.code
                    );
                }else{
                    that.$message.error('请求失败，请尝试刷新页面或重新登录')
                }
            }).catch( err=> {console.log(err)})
        },

        // 修改
        updataroles(firmupdata){
            let that = this;
            that.$refs[firmupdata].validate((valid)=>{
                if(valid){
                    let data = {};
                    for(var o in that.rolesupdata) o!=='key' ? data[o] = that.rolesupdata[o] : '';
                    console.log(that.frolirmlist[that.rolesupdata.key])
                    let updata = JSON.stringify(data)
                    // console.log(updata,data)
                    axios({
                        method: 'post',
                        url: '/api/dealer/update',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        that.centerDialog=false;
                        console.log(resp)
                        that.$message({
                            message: resp.data.message,
                            type: 'success'
                        })
                        for(var o in data) o==='state' ? that.frolirmlist[that.rolesupdata.key][o] = Number(data[o]) : that.frolirmlist[that.rolesupdata.key][o]=data[o];
                    }).catch( err=> {console.log(err)})
                }else{return}
            })
        },

        // 修改状态
        freeze(id,state,key){
            let that = this;
            if(state === 1){
                let updata = JSON.stringify({id:id,state:0})
                // console.log(updata)
                axios({
                    method: 'post',
                    url: '/api/dealer/update',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    that.frolirmlist[key].state = 0;
                }).catch( err=> {console.log(err)})
            }else{this.$message.error('账号已被冻结，请勿重复操作')}
        },

        // 拿全部的企业名称，为添加经销商和显示经销商对应的企业做准备
        async requestpartner(){
            let that = this;
            let total = 10;
            that.alldealer()
            for(var o=0;o<2;o++){
                let data = {current: 1,size: total};
                let updata = JSON.stringify(data);
                await axios({    
                    method: 'post',
                    url: '/api/enterprise/list',
                    headers: {
                        'Content-type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(o === 0){
                        // 用map挑出需要的字段重新组合，选择的上级合作伙伴
                        resp.data.code <= total ? (
                            that.selectlevel = resp.data.data.map((item)=>{
                                return{
                                    id: item['id'],
                                    name: item['name'],
                                }
                            }),o=2
                        ) : total = resp.data.code;
                    }else{
                        that.selectlevel = resp.data.data.map((item)=>{
                            return{
                                id: item['id'],
                                name: item['name'],
                            }
                        })
                    }
                }).catch( err=> {console.log(err)})
            }
            console.log(that.selectlevel)
            that.requestfrolirm()
            // that.selectlevel.sort(
            //     function paixu(value1,value2){
            //     return value1.level-value2.level;//替换为value2-value1可实现从大到小排序
            // })
            // console.log(that.selectlevel)
        },

        // 那全部的经销上姓名，创建下级经销商使用
        async alldealer(){
            let total,data,updata
            for(var o=0;o<2;o++){
                data = {current:1,size:total};
                updata = JSON.stringify(data);
                await axios({
                    method: 'post',
                    url: '/api/dealer/list',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    if(o === 0){
                        resp.data.code <= total ? (
                            that.selectdealer = resp.data.data.map((item)=>{
                                return{
                                    id: item['id'],
                                    name: item['name'],
                                    level: item['level']
                                }
                            }),o=2
                        ) : total = resp.data.code;
                    }else{
                        that.selectdealer = resp.data.data.map((item)=>{
                            return{
                                id: item['id'],
                                name: item['name'],
                                level: item['level']
                            }
                        })
                    }
                }).catch( err=> {console.log(err)})
            }
            // console.log(that.selectdealer)
            // 数组重排
            that.selectdealer.sort(
                function paixu(value1,value2){
                return value1.level-value2.level;//替换为value2-value1可实现从大到小排序
            })
        },

        // 等级选择的验证
        gradeselect(){
            that.rolesadd.level === 0 ? that.rolesadd.topid = 0 : that.rolesadd.topid = '';
            // that.rolesadd.topid = '';
            if(that.rolesadd.level-that.selectdealer[that.selectdealer.length-1].level > 1){
                // console.log(that.rolesadd.level)
                that.$message.error("没有符合条件的经销商作为上级，选项无法生效")
                that.rolesadd.level = ''
            }
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.requestpartner()
			}).catch( err=> {})
        }
    },
    created() {
        
    },
    mounted() {
        let that = this;
        that.newtoken()
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_roledealer{
    width: 100%;
    /* background-color: #ffffff; */
}
.d_rd-first,.d_rd-second{
    height: 100%;
}
/* .d_rd-title{
    padding: 10px;
    background-color: #ffffff;
} */
.d_rd-title{
    display: flex;
    justify-content: space-between;
    box-shadow: 0 0 2px #919191;
}
/* 搜索添加 */
.d_rd-t-search{
    width: 100%;
}

/* 搜索的省市级联选择器 */
.search-cascader{
    width: 100%;
}
/* 搜索的同类按钮的左边距 */
.el-button+.el-button{
    margin-left: 0;
}

.d_rd-t-num{
    vertical-align:top;
    width: 160px;
    height: 90px;
    line-height: 90px;
    background-color: #1BCAFF;
    box-shadow: 1px 0 3px #bebebe;
}
/* 列表 */
.d_rd-list{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 169px);
    box-shadow: 0 0 2px #919191;
}
.d_rd-l-table{
    width: 100%;
    color: #666666;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid  #e0e0e0;
    border-collapse: collapse;
}
.d_rd-l-table thead tr,.d_rd-l-table tbody tr:hover{
    background-color: #F2F2F2;
}
.d_rd-l-table th, .d_rd-l-table td{
    min-height: 50px;
    padding: 10px;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
/* 密码的显示 */
.d_rd-l-t-tbody-pwd:hover span:nth-child(1){
    display: none;
}
.d_rd-l-t-tbody-pwd:hover span:nth-child(2){
    display: block;
}
</style>